<template>
    <el-drawer v-model="drawerVisible" title="修改" direction="rtl" size="50%" :with-header="true">
        <el-form ref="formRef" style="max-width: 600px" :model="form" label-width="auto" label-position="top">

            <!-- 头像 -->
            <el-form-item label="头像">
                <div style="display:flex;align-items:center;">
                    <img :src="rowData.userPicture"
                        style="width:80px;height:80px;border-radius:50%;object-fit:cover;margin-right:12px" />
                    <el-upload class="avatar-uploader" :show-file-list="false" :http-request="uploadAvatar"
                        :before-upload="beforeAvatarUpload">
                        <el-button type="primary">更换头像</el-button>
                    </el-upload>
                </div>
            </el-form-item>

            <el-form-item label="用户ID">
                <el-input v-model="rowData.id" disabled />
            </el-form-item>
            <el-form-item label="注册时间">
                <el-input v-model="rowData.createTime" disabled />
            </el-form-item>

            <el-form-item label="用户名">
                <el-input v-model="rowData.userName" />
            </el-form-item>

            <!-- 手机号 -->
            <el-form-item label="手机号">
                <div style="display: flex; width: 100%">
                    <el-input v-model="rowData.userTel" />
                    <el-button style="margin-left: 8px" :disabled="smsCoolDown > 0" @click="handleSendSms">
                        {{ smsCoolDown > 0 ? `${smsCoolDown}s` : "获取验证码" }}
                    </el-button>
                </div>
            </el-form-item>

            <!-- 验证码 -->
            <el-form-item label="短信验证码">
                <div style="display: flex; width: 100%">
                    <el-input v-model="form.smsCode" placeholder="请输入验证码" />
                    <!-- <el-button style="margin-left: 8px" :disabled="!form.smsCode" @click="handleVerifySms">
                        验证
                    </el-button> -->
                </div>
            </el-form-item>

            <el-form-item label="微信绑定">
                <el-input v-model="rowData.wechat" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="handleSave">
                    保存
                </el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script lang="ts" setup>
import { adminRoleSave } from "@/api/personCenter";
import { getsendSms } from "@/api/login";
import { apiClient } from '@/utils/request';
import { ElMessage } from "element-plus";
import { ref, onMounted, onUnmounted, computed, reactive, defineProps, defineEmits, watch } from 'vue'
// 定义props接收父组件传递的数据
const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    rowData: {
        type: Object,
        default: () => ({})
    }
})
const form = reactive({

    smsCode: "",

});
const smsVerified = ref(false); // 是否已通过短信验证
const smsCoolDown = ref(0);
let smsTimer: any = null;

/*  获取验证码  */
const handleSendSms = async () => {
    if (!props.rowData.userTel) {
        ElMessage.warning("请先填写手机号");
        return;
    }
    try {
        await getsendSms(props.rowData.userTel);
        ElMessage.success("验证码已发送");
        smsCoolDown.value = 60;
        smsVerified.value = false;
        smsTimer = setInterval(() => {
            smsCoolDown.value--;
            if (smsCoolDown.value <= 0) clearInterval(smsTimer);
        }, 1000);
    } catch {
        ElMessage.error("发送失败，请重试");
    }
};
// 验证验证码
// const handleVerifySms = async () => {
//   if (!form.smsCode.trim()) {
//     ElMessage.warning("请输入验证码");
//     return;
//   }
//   try {
//     if (form.smsCode === "data.smsCode")
//       ElMessage.success("验证码正确");
//     smsVerified.value = true;
//   } catch {
//     ElMessage.error("验证码错误");
//     smsVerified.value = false;
//   }
// };
// 保存
const handleSave = () => {
    const parmas = {
        id: props.rowData.id,
        smsCode: form.smsCode,
        userPicture: props.rowData.userPicture,
        userName: props.rowData.userName,
        userTel: props.rowData.userTel,
    }
    adminRoleSave(parmas)
        .then((res) => {
            if (res.code === 200) {
                ElMessage.success('保存成功')
            }
        })
        .catch((err) => {
            console.error('发送失败:', err);
        });

}

// 定义emit用于通知父组件drawer状态变化
const emit = defineEmits(['update:visible'])

// 抽屉可见性状态
const drawerVisible = ref(props.visible)

// 监听父组件传入的visible变化
watch(() => props.visible, (newVal) => {
    drawerVisible.value = newVal
})

// 监听drawerVisible变化并通知父组件
watch(drawerVisible, (newVal) => {
    emit('update:visible', newVal)
})

// 头像
const beforeAvatarUpload = (rawFile: File) => {
    const isImage = rawFile.type.startsWith('image/');
    const isLt2M = rawFile.size / 1024 / 1024 < 2;
    if (!isImage) {
        ElMessage.error('请上传图片格式文件');
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB');
    }
    return isImage && isLt2M;
};
// 上传接口
const uploadAvatar = async ({ file }: { file: File }) => {
    try {
        const fd = new FormData();
        fd.append('file', file);
        const res = await apiClient.post('/user/upload', fd, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
        if (res.code === 200) {
            props.rowData.userPicture = res.data;
            ElMessage.success('头像上传成功');
        } else {
            ElMessage.error('上传失败');
        }
    } catch (e) {
        console.error(e);
        ElMessage.error('网络异常，上传失败');
    }
};
</script>

<style scoped lang="scss">
.header {

    height: 100px;
    background: #F7F7F7;
    border-radius: 10px;
    padding: 10px;

    .content-flag {
        display: flex;

    }

    .square {
        display: flex;
        flex-direction: column;

        padding-right: 60px;


        .label {
            font-size: 14px;
            color: #999999;
        }

        .num {
            font-family: PingFang SC, PingFang SC;
            font-weight: 800;
            font-size: 20px;
            color: #2D7AF7;
        }
    }

    .square:not(:last-child) {
        border-right: 1px solid #EEEEEE;


    }

    .square:not(:first-child) {

        padding-left: 40px;

    }




}

.tab-area {
    margin-bottom: 20px;
}

.pagination-container {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 20px;
}

.custom-pagination {
    --el-pagination-hover-bg-color: #f5f7fa;
    --el-pagination-bg-color: transparent;
    --el-pagination-text-color: #606266;
    --el-pagination-button-disabled-bg-color: #f5f7fa;
    --el-pagination-button-disabled-text-color: #c0c4cc;
}

.pagination-pages {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
}

.pagination-btn {
    min-width: 32px;
    height: 32px;
    padding: 0;
    margin: 0 4px;
    background-color: transparent;
    border: 1px solid #dcdfe6;
    color: #606266;
    font-size: 14px;
    cursor: pointer;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.pagination-btn:hover {
    color: #409eff;
}

.pagination-btn.active {
    background-color: #409eff;
    color: #fff;
    border-color: #409eff;
}

.pagination-btn.disabled {
    color: #c0c4cc;
    cursor: not-allowed;
}
</style>